package com.heima.behavior.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.heima.behavior.pojos.ApArticleLikes;
import com.heima.behavior.pojos.ApArticleUnlikes;
import com.heima.behavior.service.ArticleUnlikeService;
import com.heima.model.behavior.dtos.UnlikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ArticleUnlikeServiceImpl implements ArticleUnlikeService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult getUnLikes(UnlikesBehaviorDto dto) {
        Integer userId = AppThreadLocalUtil.getUser();
        //0 不喜欢      1 取消不喜欢
        Short type = dto.getType();
        if (type == 0){
            ApArticleUnlikes unlikes = new ApArticleUnlikes();
            unlikes.setArticleId(dto.getArticleId());
            unlikes.setUserId((long)userId);
            unlikes.setType(type);
            unlikes.setCreateTime(LocalDateTime.now());
            unlikes.setUpdateTime(LocalDateTime.now());
            mongoTemplate.save(unlikes);
        } else if (type == 1) {
            mongoTemplate.remove(Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("userId").is(userId)), ApArticleUnlikes.class);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public Boolean isUnlikes(UnlikesBehaviorDto dto) {
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("userId").is(AppThreadLocalUtil.getUser()));
        ApArticleUnlikes one = mongoTemplate.findOne(query, ApArticleUnlikes.class);
        return ObjectUtils.isNotEmpty(one);
    }




}
